package com.shuai.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shuai.common.constant.ErrorCode;
import com.shuai.common.constant.InterfaceConstant;
import com.shuai.common.exception.BusinessException;
import com.shuai.common.rps.BaseResponse;
import com.shuai.common.utils.ResultUtils;
import com.shuai.user.domain.entity.InterfaceParams;
import com.shuai.user.service.InterfaceParamsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/interface_params")

public class InterfaceParamsController {
    @Autowired
    private InterfaceParamsService interfaceParamsService;


    /**
     * 根据接口id获取接口的请求参数
     *
     * @param id 接口id
     */
    @GetMapping("/get_req_p")
    public BaseResponse<List<InterfaceParams>> getReqParamsForInterface(Long id) {
        if (id == null || id < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数错误");
        }
        LambdaQueryWrapper<InterfaceParams> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(InterfaceParams::getInterfaceId, id);
        queryWrapper.eq(InterfaceParams::getParamOrder, InterfaceConstant.reqParam);
        List<InterfaceParams> interfaceParams = interfaceParamsService.list(queryWrapper);
        return ResultUtils.success(interfaceParams);
    }

    /**
     * 根据接口id获取接口的响应参数
     *
     * @param id 接口id
     */
    @GetMapping("/get_rps_p")
    public BaseResponse<List<InterfaceParams>> getRpsParamsForInterface(Long id) {
        if (id == null || id < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数错误");
        }
        LambdaQueryWrapper<InterfaceParams> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(InterfaceParams::getInterfaceId, id);
        queryWrapper.eq(InterfaceParams::getParamOrder, InterfaceConstant.rpsParam);
        List<InterfaceParams> interfaceParams = interfaceParamsService.list(queryWrapper);
        interfaceParams = interfaceParams.stream().sorted(Comparator.comparingInt(o -> o.getParamName().length())).collect(Collectors.toList());
        return ResultUtils.success(interfaceParams);
    }

}
